package com.xk857.simpleeffect.fragment.project;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xk857.simpleeffect.R;
import com.xk857.simpleeffect.activity.ProjectPersonInfoActivity;
import com.xk857.simpleeffect.adapter.ListFriendCollaborationAdapter;
import com.xk857.simpleeffect.adapter.ListSelectFriendAdapter;
import com.xk857.simpleeffect.domain.Result;
import com.xk857.simpleeffect.domain.entity.Project;
import com.xk857.simpleeffect.domain.param.InvitationFriendProjectParam;
import com.xk857.simpleeffect.domain.param.UpdateProjectParam;
import com.xk857.simpleeffect.domain.vo.CountProjectVO;
import com.xk857.simpleeffect.domain.vo.CustomerBusinessSimpleVO;
import com.xk857.simpleeffect.domain.vo.FriendListVo;
import com.xk857.simpleeffect.enums.RequestEnum;
import com.xk857.simpleeffect.utils.CalendarUtils;
import com.xk857.simpleeffect.utils.OkHttpUtils;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xui.widget.popupwindow.ViewTooltip;
import com.xuexiang.xui.widget.toast.XToast;

import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.Period;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.function.Consumer;

import cn.hutool.core.date.LocalDateTimeUtil;
import de.hdodenhof.circleimageview.CircleImageView;

public class ProjectInfoFragment extends Fragment {

    private View view;
    private int projectId;

    private Project project;
    private EditText projectNameEdit;
    private TextView createDayText;
    private EditText remarkEdit;
    private TextView finishTimeText;
    private TextView allCountNumText;
    private TextView finishNumText;
    private TextView noNumText;
    private TextView todayCountNumText;
    private TextView delayNumText;
    private TextView delayFinishNumText;
    private LinearLayout addImgIcon;
    private RecyclerView recyclerView;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.project_fragment_info, container, false);
        initView(view);
        if (getArguments() != null) {
            projectId = getArguments().getInt("projectId");
        }
        initProjectData(projectId);
        initPopup(view);
        onUpdate();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        // 项目成员列表
        getProjectCustomerList();
    }

    /**
     * 获取项目成员列表
     */
    private void getProjectCustomerList() {
        Type type = new TypeToken<Result<List<CustomerBusinessSimpleVO>>>() {}.getType();
        String url = OkHttpUtils.BASE_URL + "/api/v1/project/customer/get/customer/list/" + projectId;
        OkHttpUtils.getInstance().get(getActivity(), url, type, true, (Consumer<List<CustomerBusinessSimpleVO>>) voList -> {
            if (getActivity() != null) {
                getActivity().runOnUiThread(() -> {
                    Gson gson = new Gson();
                    LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
                    recyclerView.setLayoutManager(layoutManager);
                    ListFriendCollaborationAdapter listFriendCollaborationAdapter = new ListFriendCollaborationAdapter(getActivity(), voList);
                    listFriendCollaborationAdapter.setItemAnimation(BaseQuickAdapter.AnimationType.AlphaIn);
                    listFriendCollaborationAdapter.setOnItemClickListener((baseQuickAdapter, view1, i) -> {
                        Intent intent = new Intent(getActivity(), ProjectPersonInfoActivity.class);
                        intent.putExtra("isBusiness", false);
                        intent.putExtra("info", gson.toJson(voList.get(i)));
                        intent.putExtra("projectId", projectId);
                        getActivity().startActivity(intent);
                    });
                    recyclerView.setAdapter(listFriendCollaborationAdapter);
                });
            }
        });
    }

    /**
     * 监听各修改框更改事件
     */
    private void onUpdate() {
        projectNameEdit.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                if (!projectNameEdit.getText().toString().equals(project.getName())) {
                    if (getActivity() != null) {
                        new MaterialDialog.Builder(getActivity()).iconRes(R.drawable.icon_info).title(R.string.info).content("您确定要修改项目名称吗？").positiveText(R.string.yes).negativeText(R.string.cancel)
                                .onPositive((dialog, which) -> {
                                    String name = projectNameEdit.getText().toString();
                                    if (name.length() == 0 || name.length() > 12) {
                                        XToast.error(getActivity(), "项目名称应在1~12位之间").show();
                                        projectNameEdit.setText(project.getName());
                                        return;
                                    }
                                    UpdateProjectParam param = new UpdateProjectParam();
                                    param.setName(name);
                                    sendUpdate(param);
                                }).onNegative((dialog, which) -> projectNameEdit.setText(project.getName())).show();
                    }

                }
            }
        });
        remarkEdit.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                if (!remarkEdit.getText().toString().equals(project.getElaborate())) {
                    if (getActivity() != null) {
                        new MaterialDialog.Builder(getActivity()).iconRes(R.drawable.icon_info).title(R.string.info).content("您确定要修改项目描述信息吗？").positiveText(R.string.yes).negativeText(R.string.cancel)
                                .onPositive((dialog, which) -> {
                                    UpdateProjectParam param = new UpdateProjectParam();
                                    param.setElaborate(remarkEdit.getText().toString());
                                    sendUpdate(param);
                                }).onNegative((dialog, which) -> remarkEdit.setText(project.getElaborate())).show();
                    }
                }
            }
        });
        // 修改目标时间
        finishTimeText.setOnClickListener(v -> {
            Calendar calendar = Calendar.getInstance();
            if (project.getFinishTime() != null) {
                calendar = CalendarUtils.getCalenderByDateTextSplit(project.getFinishTime().getYear() + "-" + (project.getFinishTime().getMonthValue() - 1) + "-" + project.getFinishTime().getDayOfMonth());
            }
            DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), com.xuexiang.xui.R.style.XUITheme_AlertDialog, (view, year, month, day) -> {
                Calendar calendar1 = Calendar.getInstance();
                month += 1;
                calendar1.set(year, month, day);
                List<Integer> finishTimeList = new ArrayList<>(3);
                finishTimeList.add(year);
                finishTimeList.add(month);
                finishTimeList.add(day);
                project.setFinishTime(finishTimeList);
                finishTimeText.setText(CalendarUtils.getDataStr(calendar1, "yyyy-MM-dd"));
                UpdateProjectParam param = new UpdateProjectParam();
                param.setFinishTime(finishTimeList);
                sendUpdate(param);
            }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
            datePickerDialog.show();
        });
    }


    public static ProjectInfoFragment newInstance(int projectId) {
        ProjectInfoFragment fragment = new ProjectInfoFragment();
        Bundle args = new Bundle();
        args.putInt("projectId", projectId);
        fragment.setArguments(args);
        return fragment;
    }

    private void initProjectData(int projectId) {
        // 1.查询项目基本信息
        Type type = new TypeToken<Result<Project>>() {
        }.getType();
        String url = OkHttpUtils.BASE_URL + "/api/v1/project/" + projectId;
        OkHttpUtils.getInstance().get(getActivity(), url, type, true, (Consumer<Project>) pro -> {
            if (getActivity() != null) {
                getActivity().runOnUiThread(() -> {
                    this.project = pro;
                    projectNameEdit.setText(project.getName());
                    int days = Period.between(project.getCreateTime().toLocalDate(), LocalDate.now()).getDays();
                    if (days == 0) {
                        createDayText.setText("项目今天刚成立");
                    } else {
                        createDayText.setText(String.format(Locale.CHINA, "项目已成立 %d 天", days));
                    }

                    remarkEdit.setText(project.getElaborate());
                    if (project.getFinishTime() == null) {
                        finishTimeText.setText("暂无目标时间");
                    } else {
                        finishTimeText.setText(String.format(Locale.CHINA, "目标时间：%s", LocalDateTimeUtil.format(project.getFinishTime(), "yyyy-MM-dd")));
                    }
                });
            }
        });

        // 2.查询项目统计信息
        Type countType = new TypeToken<Result<CountProjectVO>>() {
        }.getType();
        String countUrl = OkHttpUtils.BASE_URL + "/api/v1/project/count/number/" + projectId;
        OkHttpUtils.getInstance().get(getActivity(), countUrl, countType, true, (Consumer<CountProjectVO>) vo -> {
            if (getActivity() != null) {
                getActivity().runOnUiThread(() -> {
                    allCountNumText.setText(String.valueOf(vo.getAllCount()));
                    finishNumText.setText(String.valueOf(vo.getYesCount()));
                    noNumText.setText(String.valueOf(vo.getNoCount()));
                    todayCountNumText.setText(String.valueOf(vo.getTodayCount()));
                    delayNumText.setText(String.valueOf(vo.getTodayDelayCount()));
                    delayFinishNumText.setText(String.valueOf(vo.getDelayFinishCount()));
                });
            }
        });
    }

    private void initView(View view) {
        projectNameEdit = view.findViewById(R.id.project_name_edit);
        createDayText = view.findViewById(R.id.create_day_text);
        remarkEdit = view.findViewById(R.id.remark_edit);
        finishTimeText = view.findViewById(R.id.finish_time_text);
        allCountNumText = view.findViewById(R.id.all_count_num_text);
        finishNumText = view.findViewById(R.id.finish_num_text);
        noNumText = view.findViewById(R.id.no_num_text);
        todayCountNumText = view.findViewById(R.id.today_count_num_text);
        delayNumText = view.findViewById(R.id.delay_num_text);
        delayFinishNumText = view.findViewById(R.id.delay_finish_num_text);
        addImgIcon = view.findViewById(R.id.add_img_icon);

        addImgIcon.setOnClickListener(v -> addFriendInProject());
        recyclerView = view.findViewById(R.id.recycler_view);
    }

    /**
     * 邀请协作人进入项目逻辑，弹出底部对话框
     */
    private void addFriendInProject() {
        // 获取获取项目成员ids
        getProjectCustomer(customerIds -> {
            // 获取好友信息
            Type type = new TypeToken<Result<List<FriendListVo>>>() {}.getType();
            OkHttpUtils.getInstance().get(getActivity(), RequestEnum.GET_MY_FRIEND_LIST, type, true, (Consumer<List<FriendListVo>>) friendListVoList -> {
                if (getActivity() != null) {
                    getActivity().runOnUiThread(() -> {
                        // 构建底部对话框
                        BottomSheetDialog dialog = new BottomSheetDialog(getActivity(), R.style.bottom_sheet_dialog);
                        dialog.setContentView(R.layout.select_person_bottom_dialog);

                        // 顶部右侧按钮点击隐藏
                        CircleImageView circleImageView = dialog.findViewById(R.id.hide_img_view);
                        circleImageView.setOnClickListener(v -> dialog.dismiss());

                        // 获取底部确定按钮
                        Button addEnterBtn = dialog.findViewById(R.id.add_enter_btn);

                        // 协作人适配器
                        RecyclerView friendRecycleView = dialog.findViewById(R.id.recycler_view);
                        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
                        friendRecycleView.setLayoutManager(layoutManager);

                        // 记录用户选中的id
                        final List<Long>[] selectFriendIds = new List[]{new ArrayList<>()};
                        ListSelectFriendAdapter listFriendAdapter = new ListSelectFriendAdapter(getActivity(), friendListVoList, customerIds, friendIds -> {
                            addEnterBtn.setText("确定 (" + friendIds.size() + ")");
                            addEnterBtn.setEnabled(friendIds.size() > 0);
                            selectFriendIds[0] = friendIds;
                        });
                        addEnterBtn.setOnClickListener(v -> {
                            sendAddFriendInProject(selectFriendIds[0], dialog);
                        });

                        listFriendAdapter.setItemAnimation(BaseQuickAdapter.AnimationType.AlphaIn);
                        friendRecycleView.setAdapter(listFriendAdapter);
                        dialog.show();
                    });
                }
            });
        });

    }

    /**
     * 发送邀请好友进入项目请求
     *
     * @param selectFriendId 好友ids
     * @param dialog         对话框
     */
    private void sendAddFriendInProject(List<Long> selectFriendId, BottomSheetDialog dialog) {
        Type type = new TypeToken<Result<Integer>>() {}.getType();
        InvitationFriendProjectParam param = new InvitationFriendProjectParam();
        param.setProjectId(projectId);
        param.setCustomerIdList(selectFriendId);
        OkHttpUtils.getInstance().post(getActivity(), RequestEnum.ADD_FRIEND_TO_PROJECT, type, param, true, (Consumer<Integer>) errorNum -> {
            if (getActivity() != null) {
                getActivity().runOnUiThread(() -> {
                    if (errorNum == 0) {
                        XToast.success(getActivity(), "邀请成功").show();
                    } else {
                        XToast.warning(getActivity(), "成功" + (selectFriendId.size() - errorNum) + "条，失败" + errorNum + "条").show();
                    }
                    dialog.dismiss();
                    // 重新获取项目成员列表
                    getProjectCustomerList();
                });
            }
        });
    }

    /**
     * 获取项目成员ids
     */
    private void getProjectCustomer(Consumer<List<Long>> consumer) {
        Type type = new TypeToken<Result<List<Long>>>() {
        }.getType();
        String url = OkHttpUtils.BASE_URL + "/api/v1/project/customer/customer/ids/" + projectId;
        OkHttpUtils.getInstance().get(getActivity(), url, type, true, (Consumer<List<Long>>) customerIds -> {
            if (getActivity() != null) {
                getActivity().runOnUiThread(() -> consumer.accept(customerIds));
            }
        });
    }

    /**
     * 发送修改项目信息请求
     */
    private void sendUpdate(UpdateProjectParam param) {
        param.setId(projectId);
        Type type = new TypeToken<Result<Project>>() {
        }.getType();
        OkHttpUtils.getInstance().put(getActivity(), RequestEnum.ADD_PROJECT, type, param, true, (Consumer<Project>) pro -> {
            if (getActivity() != null) {
                getActivity().runOnUiThread(() -> {
                    this.project = pro;
                    projectNameEdit.setText(project.getName());
                    int days = Period.between(project.getCreateTime().toLocalDate(), LocalDate.now()).getDays();
                    if (days == 0) {
                        createDayText.setText("项目今天刚成立");
                    } else {
                        createDayText.setText(String.format(Locale.CHINA, "项目已成立 %d 天", days));
                    }
                    remarkEdit.setText(project.getElaborate());
                    if (project.getFinishTime() == null) {
                        finishTimeText.setText("暂无目标时间");
                    } else {
                        finishTimeText.setText(String.format(Locale.CHINA, "目标时间：%s", LocalDateTimeUtil.format(project.getFinishTime(), "yyyy-MM-dd")));
                    }
                });
            }
        });
    }


    /**
     * 初始化控件提示信息
     */
    private void initPopup(View view) {
        LinearLayout todayLayout = view.findViewById(R.id.today_num_layout);
        todayLayout.setOnClickListener(v -> ViewTooltip.on(todayLayout).color(Color.BLACK).position(ViewTooltip.Position.BOTTOM).align(ViewTooltip.ALIGN.START).text("今日完成加还未完成的任务数量").show());
        LinearLayout delayLayout = view.findViewById(R.id.delay_num_layout);
        delayLayout.setOnClickListener(v -> ViewTooltip.on(delayLayout).color(Color.BLACK).position(ViewTooltip.Position.BOTTOM).align(ViewTooltip.ALIGN.START).text("延期且未完成的任务数量").show());
        LinearLayout delayFinishLayout = view.findViewById(R.id.delay_finish_num_layout);
        delayFinishLayout.setOnClickListener(v -> ViewTooltip.on(delayFinishLayout).color(Color.BLACK).position(ViewTooltip.Position.BOTTOM).align(ViewTooltip.ALIGN.START).text("延期且已完成的任务数量").show());
        LinearLayout allLayout = view.findViewById(R.id.all_num_layout);
        allLayout.setOnClickListener(v -> ViewTooltip.on(allLayout).color(Color.BLACK).position(ViewTooltip.Position.BOTTOM).align(ViewTooltip.ALIGN.START).text("所有任务的数量").show());
        LinearLayout finishLayout = view.findViewById(R.id.finish_num_layout);
        finishLayout.setOnClickListener(v -> ViewTooltip.on(finishLayout).color(Color.BLACK).position(ViewTooltip.Position.BOTTOM).align(ViewTooltip.ALIGN.START).text("已完成任务的数量").show());
        LinearLayout noFinishLayout = view.findViewById(R.id.no_finish_num_layout);
        noFinishLayout.setOnClickListener(v -> ViewTooltip.on(noFinishLayout).color(Color.BLACK).position(ViewTooltip.Position.BOTTOM).align(ViewTooltip.ALIGN.START).text("未完成任务的数量").show());
    }
}
